#!/usr/bin/env groovy
package com.yidao.www
@Grab('com.urswolfer.gerrit.client.rest:gerrit-rest-java-client:0.9.5')
@Grab('com.google.code.gson:gson:2.8.5')
import com.urswolfer.gerrit.client.rest.*
import com.google.gerrit.extensions.api.*
import com.google.gerrit.extensions.common.*
import com.google.gerrit.extensions.client.*
import com.google.gson.*;

def getGerritResource(libName){
    
    def gerritProfile = gerritProfile()
    def host = gerritProfile.host
    def user = gerritProfile.user
    def pwd = gerritProfile.pwd
    GerritRestApiFactory gerritRestApiFactory = new GerritRestApiFactory();
    // GerritAuthData.Basic authData = new GerritAuthData.Basic("http://192.168.30.243:8888/", "gerrit", "91A7Omr2Ja43P+m8JI30cm6NYineNUqWucwmw/BqcQ");
    GerritAuthData.Basic authData = new GerritAuthData.Basic(host, user, pwd);
    GerritApi gerritApi = gerritRestApiFactory.create(authData);
    // Gson gson = new Gson()
    Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
    List<ChangeInfo> changes = gerritApi.changes().query("status:open+project:${libName}").withOption(ListChangesOption.CURRENT_REVISION).withOption(ListChangesOption.CURRENT_COMMIT).withOption(ListChangesOption.DOWNLOAD_COMMANDS).get();
    def map = [:]
    def list = []
    changes.each{ ci ->
        println '====================================================================================================================='
        def cherryPickCmd = ci.revisions.get(ci.currentRevision).fetch.ssh.commands.get('Cherry Pick')
        def refSpec = ci.revisions.get(ci.currentRevision).ref
        println 'Cherry Pick Command: ' + gson.toJson(cherryPickCmd)
        println 'RefSpec: ' + gson.toJson(refSpec)
        println '====================================================================================================================='
        map[refSpec] = cherryPickCmd
        def revisions = ci.revisions
        revisions.each{ x,y ->
            println(gson.toJson(y.ref))
            list.add(y.ref)
        }
        println(gson.toJson(ci.revisions))
    }
    
    // println 'list: ' + list
    println 'map: ' + map
    // return list.join(',')
    return map

}